import type { ColumnsType, TableProps } from 'antd/es/table';
import React, { createRef, useState, useEffect, useMemo } from 'react';
import { Table, Button, Form, Input, Select, Col, Cascader, message } from 'myselfantd';
import {
  addThreshold,
  getDeviceList,
  updateThreshold,
  getPage,
  getAlarmParamByCode,
  getThresholdFieldList,
} from '../api';
import type {
  addThresholdParams,
  updateThresholdParams,
  getPageParams,
  getAlarmParamByCodeParams,
} from '../api';
interface DataType {
  code: number;
  name: string;
  type: string;
  value: number;
  unit: number;
  duration: number;
  remark: string;
  editable: boolean;
}
interface Props {
  data?: any;
  type?: any;
  title?: any;
  onFinish?: Function;
}
const App = ({ data, type, title, onFinish }: Props) => {
  let searchRef = createRef<any>();
  const [machineCode, setMachineCode] = useState('');
  const [deviceSpuId, setDeviceSpuId] = useState('');
  const [tempCode, setTempCode] = useState('');
  const [formColumns, setFormColumns] = useState<any>([]);
  const [fields, setFields] = useState([] as any);
  const [selectData, setSelectData] = useState<any>([]);
  useEffect(() => {
    if (tempCode) {
      let params: getAlarmParamByCodeParams = { machineTypeCode: tempCode };
      getAlarmParamByCode(params).then(({ result }) => {
        setSelectData(result);
      });
    }
  }, [tempCode]);
  useEffect(() => {
    if (data) {
      searchRef.current.setForm({ name: data.machineTypeName, type: data.machineName });
      getThresholdFieldList({ id: data.id }).then(({result}: any) => {
        setFields(result.map((item: any, index: any) => ({ sortkey: index + 1, ...item })));
      });
      setTempCode(data.machineTypeCode);
    }
  }, [data]);
  return (
    <>
      <div className={'myantd '} style={{ height: '30px', position: 'relative' }}>
        <h2>{title}</h2>
        {data ? (
          <Button
            type="primary"
            style={{ position: 'absolute', right: 0, top: 0 }}
            onClick={() => {
              if (!fields.length) {
                message.warning('阈值规则列表不能为空');
                return false;
              }
              let params: updateThresholdParams = {
                fieldList: fields,
                id: data.id,
              };
              updateThreshold(params).then((res: any) => {
                message.success('数据更新成功');
                onFinish?.();
              });
            }}
          >
            更新
          </Button>
        ) : (
          <Button
            type="primary"
            style={{ position: 'absolute', right: 0, top: 0 }}
            onClick={() => {
              if (!machineCode || !deviceSpuId) {
                message.warning('请选择选择农机类型和设备');
                return false;
              }
              if (!fields.length) {
                message.warning('阈值规则列表不能为空');
                return false;
              }
              let params: addThresholdParams = {
                fieldList: fields,
                machineCode,
              };
              addThreshold(params).then((res: any) => {
                message.success('数据创建成功');
                onFinish?.();
              });
            }}
          >
            保存
          </Button>
        )}
      </div>
      <Form.Search
        onSearchRef={searchRef}
        type={true}
        columns={useMemo(
          () => [
            {
              name: 'name',
              render: () => (
                <Cascader
                  disabled={!!data}
                  request={async () => {
                    let { result } = await getDeviceList({ category: 0 });
                    return result;
                  }}
                  fieldNames={{ label: 'name', value: 'id' }}
                  placeholder="选择农机类型"
                  allowClear={false}
                />
              ),
            },
            {
              name: 'type',
              render: () => (
                <Select
                  disabled={!!data}
                  reload={deviceSpuId}
                  fieldNames={{ name: 'name', value: 'code' }}
                  request={async () => {
                    if (deviceSpuId) {
                      let pageParams: getPageParams = {
                        deviceSpuId: deviceSpuId,
                        pageIndex: '1',
                        pageSize: '20',
                      };
                      let { result } = await getPage(pageParams);
                      setFormColumns([...result.data]);
                      return result.data;
                    } else {
                      return [];
                    }
                  }}
                  placeholder="选择设备"
                  allowClear={false}
                />
              ),
            },
          ],
          [deviceSpuId],
        )}
        onChange={(filed: any) => {
          setDeviceSpuId(filed.name[filed.name.length - 1]);
          setMachineCode(filed.type);
          let code: any = formColumns.find((item: any) => filed.type === item.code);
          setTempCode(code?.tempCode);
        }}
      ></Form.Search>
      <Table.Form
        scroll={{ scrollToFirstRowOnChange: true, y: 200 }}
        pagination={{
          locale: {
            page: '页',
          },
          showTotal: (total: any) => `共 ${total} 条数据`,
        }}
        value={fields}
        columns={useMemo(
          () => [
            {
              title: '序号',
              dataIndex: 'sortkey',
              width: 180,
              onCell: (record: any) => {
                return {
                  filed: 'sortkey',
                  record,
                };
              },
            },
            {
              title: '工矿名称',
              dataIndex: 'code',
              showSorterTooltip: false,
              onCell: (record: any) => ({
                editable: true,
                filed: 'code',
                record,
                rules: [
                  {
                    required: true,
                    message: `工矿名称必选`,
                  },
                ],
                render: () => (
                  <Select
                    reload={selectData.length}
                    fieldNames={{ name: 'name', value: 'code' }}
                    request={async () => selectData}
                    placeholder="选择工矿名称"
                    allowClear={false}
                  />
                ),
                viewRender: (_: any) => {
                  return selectData.find((item: any) => item.code === _)?.name;
                },
              }),
            },
            {
              title: '报警类型',
              dataIndex: 'type',
              showSorterTooltip: false,
              width: 180,
              onCell: (record: any) => ({
                editable: true,
                filed: 'type',
                record,
                rules: [
                  {
                    required: true,
                    message: `报警类型必选`,
                  },
                ],
                render: () => (
                  <Select placeholder="选择报警类型" allowClear={false}>
                    <Select.Option value={0} key="0">
                      等于阈值
                    </Select.Option>
                    <Select.Option value={1} key="1">
                      小于阈值
                    </Select.Option>
                    <Select.Option value={2} key="2">
                      大于阈值
                    </Select.Option>
                  </Select>
                ),
                viewRender: (_: any) => {
                  return ['等于阈值', '小于阈值', '大于阈值'][_];
                },
              }),
            },
            {
              title: '设置阈值',
              dataIndex: 'value',
              showSorterTooltip: false,
              width: 180,
              onCell: (record: any) => ({
                editable: true,
                filed: 'value',
                record,
                rules: [
                  {
                    required: true,
                    message: `阈值必填`,
                  },
                ],
              }),
            },
            {
              title: '单位',
              dataIndex: 'unit',
              showSorterTooltip: false,
              onCell: (record: any) => ({
                editable: true,
                filed: 'unit',
                record,
                rules: [
                  {
                    required: true,
                    message: `单位必选`,
                  },
                ],
                render: () => (
                  <Select
                    reload={selectData.length}
                    fieldNames={{ name: 'unit', value: 'unit' }}
                    request={async () => selectData}
                    placeholder="选择单位"
                    allowClear={false}
                  />
                ),
              }),
            },
            {
              title: '计数持续时间',
              dataIndex: 'duration',
              showSorterTooltip: false,
              width: 150,
              onCell: (record: any) => ({
                editable: true,
                filed: 'duration',
                record,
                rules: [
                  {
                    required: true,
                    message: `计数持续时间必填`,
                  },
                ],
                render: () => <Input placeholder="计数持续时间" suffix=" s" />,
                viewRender: (_: any) => `${_} s`,
              }),
            },
          ],
          [selectData.length],
        )}
        onChange={(data: any) => {
          setFields(data);
        }}
        createRowData={
          tempCode || data
            ? (val: any): object => {
                return { code: '', type: 0, value: '1', unit: '', duration: '1' };
              }
            : false
        }
      />
    </>
  );
};

export default App;
